package com.coscoshipping.rams.demo.cronjob;

import com.coscoshipping.rams.demo.pojo.vo.BusinessSalesVO;
import com.coscoshipping.rams.demo.pojo.vo.TicketSalesVO;
import com.coscoshipping.rams.demo.service.IBlockAnalysisService;
import com.coscoshipping.rams.demo.service.IBusinessSalesStatisticsService;
import com.coscoshipping.rams.demo.service.ITicketSalesStatisticsService;
import com.coscoshipping.rams.demo.utils.HttpUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDate;
import java.util.Date;
import java.util.List;

@Component
public class ScheduledTasks {

    @Autowired
    private IBlockAnalysisService blockAnalysisService;

    @Autowired
    private IBusinessSalesStatisticsService businessSalesStatisticsService;

    @Autowired
    private ITicketSalesStatisticsService ticketSalesStatisticsService;


    /**
     * 每天凌晨零点零五分执行的定时任务
     */
    @Scheduled(cron = "0 5 0 * * ?")
    public void syncDataDaily() {
        try {
            // 获取昨天的日期
            LocalDate yesterday = LocalDate.now().minusDays(1);

            // 调用 HttpUtils 获取数据
            List<BusinessSalesVO> businessSales = HttpUtils.businessSales(yesterday.atStartOfDay());

            // 营业销售统计信息表
            businessSalesStatisticsService.saveOrUpdateData(businessSales);

            // 调用 HttpUtils 获取数据
            List<TicketSalesVO> ticketSales = HttpUtils.ticketSales(yesterday.atStartOfDay());

            // 票型销售统计表
            ticketSalesStatisticsService.saveOrUpdateData(ticketSales);

            System.out.println("定时任务执行成功，数据已同步到数据库");
        } catch (Exception e) {
            System.err.println("定时任务执行失败: " + e.getMessage());
            e.printStackTrace();
        }
    }



    // 每5秒执行一次
//    @Scheduled(fixedRate = 5000)
    public void reportCurrentTime() {
        System.out.println("每5秒执行一次，现在时间：" + new Date());
        // 新增block记录
        blockAnalysisService.addBlockAnalysis();

        //
    }

    // 每1秒执行一次
//    @Scheduled(fixedRate = 1000)
    public void currentTime() {
        System.out.println("每1秒执行一次，现在时间：" + new Date());
    }

    // 使用Cron表达式，每天上午10点执行
    @Scheduled(cron = "0 0 10 * * ?")
    public void performTaskUsingCron() {
        System.out.println("执行定时任务");
    }
}